/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import me.zhengjie.modules.system.domain.SiteUser;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.SiteUserRepository;
import me.zhengjie.modules.system.service.SiteUserService;
import me.zhengjie.modules.system.service.dto.SiteUserDto;
import me.zhengjie.modules.system.service.dto.SiteUserQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.SiteUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author HeHui
* @date 2021-12-20
**/
@Service
@RequiredArgsConstructor
public class SiteUserServiceImpl implements SiteUserService {

    private final SiteUserRepository siteUserRepository;
    private final SiteUserMapper siteUserMapper;
    private final DeptService deptService;
    private final me.zhengjie.modules.system.mapper.SiteUserMapper siteMapper;

    @Override
    public Map<String,Object> queryAll(SiteUserQueryCriteria criteria, Pageable pageable){
        Page<SiteUser> page = siteUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(siteUserMapper::toDto));
    }

    @Override
    public List<SiteUserDto> queryAll(SiteUserQueryCriteria criteria){
        return siteUserMapper.toDto(siteUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public SiteUserDto findById(Long id) {
        SiteUser siteUser = siteUserRepository.findById(id).orElseGet(SiteUser::new);
        if (siteUser == null) {
            return null;
        }
        // ValidationUtil.isNull(siteUser.getId(),"SiteUser","id",id);
        return siteUserMapper.toDto(siteUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SiteUserDto create(SiteUser resources) {
        siteMapper.insertSelective(resources);
        return siteUserMapper.toDto(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SiteUser resources) {
        siteMapper.updateByPrimaryKeySelective(resources);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            siteUserRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<SiteUserDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        List<Long> deptIds = all.stream().filter(v -> v.getDeptId() != null).map(SiteUserDto::getDeptId).distinct().collect(Collectors.toList());
        Map<Long, String> deptMap = deptService.getDeptName(deptIds);
        for (SiteUserDto siteUser : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("站点", deptMap.get(siteUser.getDeptId()));
            map.put("站长名称", siteUser.getSiteUserName());
            map.put("站长手机", siteUser.getSiteUserMobile());
            map.put("最后更改时间", siteUser.getLastUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }


    /**
     * 列表
     *
     * @param criteria 标准
     * @param pageable 可分页
     * @return {@link PageInfo}<{@link SiteUserDto}>
     */
    @Override
    public PageInfo<SiteUserDto> page(SiteUserQueryCriteria criteria,  Pageable pageable) {
        return PageHelper.startPage(pageable.getPageNumber(), pageable.getPageSize()).doSelectPageInfo(() -> siteMapper.findList(criteria));
    }


    /**
     * 存在
     *
     * @param id id
     * @return boolean
     */
    @Override
    public boolean exists(long id) {
        return siteUserRepository.existsByDeptId(id);
    }

    /**
     * 删除在部门id
     *
     * @param ids id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteInDeptId(Long[] ids) {
        siteUserRepository.deleteByDeptIdIn(Arrays.asList(ids));
    }
}